import base64
import json
import time
from functional import seq

import requests
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains


def base64_api(uname, pwd, b64, typeid):
    data = {"username": uname, "password": pwd, "typeid": typeid, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/predict", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        # ！！！！！！！注意：返回 人工不足等 错误情况 请加逻辑处理防止脚本卡死 继续重新 识别
        return result["message"]


if __name__ == '__main__':
    # 发起访问
    url = 'https://passport.jd.com/uc/login?ltype=logout'
    service = Service('chromedriver.exe')
    web = WebDriver(service=service)
    web.get(url)

    login_name = web.find_element(By.XPATH, '//*[@id="loginname"]')
    pwd = web.find_element(By.XPATH, '//*[@id="nloginpwd"]')
    login = web.find_element(By.XPATH, '//*[@id="formlogin"]/div[5]')
    login_name.send_keys('13370895148')
    pwd.send_keys('adcbtug0189')
    login.click()
    time.sleep(3)
    slide = web.find_element(By.XPATH, '//*[@id="JDJRV-wrap-loginsubmit"]/div')
    security = web.find_element(By.XPATH, '//*[@id="JDJRV-wrap-loginsubmit"]/div').screenshot_as_base64
    result = base64_api('RockyLee', 'Adcbtug0189', security, 53)
    result_list = seq(result.split(',')).map(lambda r: r.strip()).to_list()
    action = ActionChains(web)
    action.click_and_hold(slide).move_by_offset(*result_list).release().perform()
    print(result)
    time.sleep(10)
    print('测试信息')
